package com.tianhe.visitormanagement.server.impl;

import com.tianhe.device.domain.Rfid;
import com.tianhe.device.feign.RemoteRfidService;
import com.tianhe.visitormanagement.domain.Trace;
import com.tianhe.visitormanagement.mapper.TraceMapper;
import com.tianhe.visitormanagement.server.common.TCPHandlerAbstract;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.SocketAddress;
import java.util.*;
import java.util.stream.Collectors;

import static com.tianhe.common.enums.DeviceType.RFID;

/**
 * @Author ：dongchao
 * @Date ：Created in 11:00 2022/3/7
 */
@Slf4j
@Component
public class RfidTCPHandlerImpl extends TCPHandlerAbstract {

    @Autowired
    private TraceMapper traceMapper;

    @Autowired
    private RemoteRfidService remoteRfidService;
    /**
     * description:
     * @return void
     * @date: 2022/3/7 13:41
     * @throws 
     * @param ctx
     * @param strings
     */
    @Override
    public void parseTcpData(ChannelHandlerContext ctx, String[] strings) throws InterruptedException {
        List<Map<String, Object>> mapList = dataframeParse(strings);
        SocketAddress address = ctx.channel().remoteAddress();
        String str = address.toString();
        String ip = str.substring(1, str.indexOf(":"));//获取当前连接客户端ip
        Map ipMap = new HashMap();
        ipMap.put("ip", ip);
        System.out.println("开始睡"+ip);
        Thread.sleep(20000);
        System.out.println(mapList.toString());
        List<Trace> traceList = mapList.stream().map(s -> {
            Trace trace = new Trace();
            trace.setRfidCardNumber((String) s.get("epcid"));
            trace.setDeviceType(RFID.getCode());
            trace.setRecordTime((Date) s.get("createTime"));
            trace.setStatus(1L);//todo
            trace.setAbnormalReason(null);//todo
            return trace;
        }).collect(Collectors.toList());
        System.out.println("醒了"+ip);
        traceMapper.insertTraceList(traceList,ip);
    }
    
    /**
     * description:数据帧解析函数
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @date: 2022/3/7 13:41
     * @throws 
     * @param hexStrs 获取到的每一帧的十六进制字符串数组
     */
    public static List<Map<String, Object>> dataframeParse(String[] hexStrs) {
        List<Map<String, Object>> data = new ArrayList<>();
        Map<String, Object> data1 = new HashMap<>();
        //目标个数
        int num = hexStrs.length / 18;
//        //帧序号
        if (num == 0) {
            log.info("心跳帧数据————————————————————");
            return data;
        }
        String[] tmp;
        int index = 0;

        for (int i = 1; i <= num; i++) {
            //多个目标数据进行截取
            System.out.println(hexStrs.toString()+"=="+hexStrs.length);
            String[] strings = Arrays.copyOfRange(hexStrs, index, index + 18);
            tmp = targetParse(strings);
            data1.put("address", tmp[0]);//addess
            data1.put("epcid", tmp[1]);//epcid
            data1.put("createTime", new Date());//epcid
            data.add(data1);
            index += 18;
        }
        return data;
    }

    /**
     * 解析RFID检测到的单个目标信息
     * 字段说明如下：属性、下标、描述
     * epcId        4-16 电子标签id
     * adrress  1 读写器地址
     *
     * @param targetStrs 目标的十六进制字符串数组
     * @return 目标各属性值
     */
    public static String[] targetParse(String[] targetStrs) {
        String[] target = new String[2];
        String adrress = String.valueOf(Integer.valueOf(targetStrs[1], 16));
        target[0] = adrress;
        String epcId = "";
        for (int i = 4; i < targetStrs.length-2; i++) {
            epcId += String.valueOf(Integer.valueOf(targetStrs[i], 16));
        }
        target[1] = epcId;
        return target;
    }

    /**
     * description:update status by ip
     * @return void
     * @date: 2022/3/7 13:45
     * @param ctx
     * @param status
     * @throws
     */
    @Override
    public void updateByIp(ChannelHandlerContext ctx, long status) {
        SocketAddress address = ctx.channel().remoteAddress();
        String str = address.toString();
        String ip = str.substring(1, str.indexOf(":"));//获取当前连接客户端ip
        Rfid rfid = new Rfid();
        rfid.setStatus(status);
        rfid.setIp(ip);
        System.out.println(rfid.toString());
        remoteRfidService.updateByIp(rfid);//更新设备状态为在线
    }
}
